package com.xingkeduo.service.cms.marketing.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.dao.TActivityDaysMapper;
import com.xingkeduo.dao.TMarketingCardMapper;
import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.dao.TMarketingCouponMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCardMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponBagMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponMapper;
import com.xingkeduo.dao.TMarketingUseHistoryCardMapper;
import com.xingkeduo.dao.TMarketingUseHistoryCouponMapper;
import com.xingkeduo.dao.TMarketingUseHistoryMapperSpec;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.feign.MessageFeignService;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponExample;
import com.xingkeduo.model.example.TMarketingUseHistoryCardExample;
import com.xingkeduo.model.example.TMarketingUseHistoryCouponExample;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCard;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCoupon;
import com.xingkeduo.model.po.TMarketingUseHistory;
import com.xingkeduo.model.po.TMarketingUseHistoryCard;
import com.xingkeduo.model.po.TMarketingUseHistoryCoupon;
import com.xingkeduo.model.vo.MarketingReceiveHistoryResponseVo;
import com.xingkeduo.service.cms.marketing.MarketingReceiveService;
import com.xingkeduo.service.consume.UserService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.tool.ResponseMessage;

@Service(value="marketingReceiveService")
public class MarketingReceiveServiceImpl implements MarketingReceiveService {
	Logger logger = LoggerFactory.getLogger(MarketingReceiveServiceImpl.class);
	@Autowired
	ManageUserFeignService manageUserFeignService;
	@Autowired
	TActivityDaysMapper tActivityDaysMapper;
	@Autowired
	UserService userService;
	@Autowired
	MessageFeignService messageFeignService;
	@Autowired
	TMarketingReceiveHistoryCouponMapper tMarketingReceiveHistoryCouponMapper;
	@Autowired
	TMarketingReceiveHistoryCardMapper tMarketingReceiveHistoryCardMapper;
	@Autowired
	TMarketingReceiveHistoryCouponBagMapper tMarketingReceiveHistoryCouponBagMapper;
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;
	@Autowired
	TMarketingCardMapper tMarketingCardMapper;
	@Autowired
	TMarketingCouponMapper tMarketingCouponMapper;
	@Autowired
	TMarketingUseHistoryCouponMapper tMarketingUseHistoryCouponMapper;
	@Autowired
	TMarketingUseHistoryCardMapper tMarketingUseHistoryCardMapper;
	@Autowired 
	TMarketingUseHistoryMapperSpec tMarketingUseHistoryMapperSpec;

	@Override
	public ResponseMessage pushExpirationReminder() {
		logger.info("【推送】到期推送开始");
		List<TMarketingReceiveHistory> requestList = new ArrayList<>();
		Date startDate = DateUtils.getCurdate();
		startDate = DateUtils.addSomeDays(startDate, 3);
		Date endDate = DateUtils.addSomeDays(startDate, 1);
		// 领取券记录
		TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
		example.createCriteria().andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
				.andUseEndTimeBetween(startDate, endDate);
		List<TMarketingReceiveHistoryCoupon> couponhistoryList = tMarketingReceiveHistoryCouponMapper
				.selectByExample(example);
		if (!CollectionUtils.isEmpty(couponhistoryList)) {
			requestList.addAll(couponhistoryList);
		}
		// 领取卡记录
		TMarketingReceiveHistoryCardExample cardnExample = new TMarketingReceiveHistoryCardExample();
		cardnExample.createCriteria().andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
				.andUseEndTimeBetween(startDate, endDate);
		List<TMarketingReceiveHistoryCard> cardhistoryList = tMarketingReceiveHistoryCardMapper
				.selectByExample(cardnExample);
		if (!CollectionUtils.isEmpty(cardhistoryList)) {
			requestList.addAll(cardhistoryList);
		}
		// 推送
		requestList.stream().forEach(history -> {
			try {
				String couponType = MarketingServiceTypeEnum.parse(history.getServiceType()).getDesc();
				messageFeignService.pushSendExpireMessage(history.getUserId().toString(), history.getMarketingName(),
						DateUtils.formatDate(history.getUseEndTime(), DateUtils.DATE_FORMAT), couponType);
				logger.info("【推送】提醒成功 historyId:{},marketingType:{},userId:{}",history.getId(),history.getMarketingType(),history.getUserId());
				if(history.getUserId().equals(Long.valueOf("5120778"))) {
					logger.info("大辉发券"+history.getId());
				}
			} catch (Exception e) {
				logger.error("【3天到期推送失败】history:{},e:{}", JSON.toJSONString(history), e);
			}
		});
		logger.info("【推送】到期推送结束");
		return ResponseMessage.ok();
	}
	
	public MarketingReceiveHistoryResponseVo buildMarketingReceiveHistoryResponse(TMarketingReceiveHistory history){
		MarketingReceiveHistoryResponseVo responseVo = new MarketingReceiveHistoryResponseVo();
		BeanUtils.copyProperties(history, responseVo);
		responseVo.setCouponBagType(history.getCouponBagType());
		responseVo.setCouponBagName(history.getMarketingName());
		Map<String,String> returnMap = userService.queryOnlyUserInfosByUserId(history.getUserId());
		if(MapUtils.isNotEmpty(returnMap)) {
			responseVo.setUserInfo(history.getUserId()+"_"+returnMap.get("name"));
			responseVo.setUserMobile(returnMap.get("phone"));
		}
		return responseVo;
	}
	
	@Override
	public ResponseMessage getReceiveLink(Long marketingId, Integer marketingType) {
		TMarketing marketing = selectByPrimaryKey(marketingId, marketingType);
		// new Base64Encoder().encode(marketingId.toString().getBytes())
		Map json = new HashMap();
		json.put("url_web", Constant.RECEIVE_MARKETING_PATH+"/mobile3/oauth2/state/1009/shop_number/" + marketingId
				+ "/product_id/" + marketing.getMarketingType() + "/product_num/sweep_code");
		json.put("url_weChat_subscription", "");
		return ResponseMessage.ok(json);
	}

	public TMarketing selectByPrimaryKey(Long supportBusinessId, Integer marketingType) {
		if (marketingType.equals(MarketingTypeEnum.COUPON.getCode())) {
			return tMarketingCouponMapper.selectByPrimaryKey(supportBusinessId);
		} else if (marketingType.equals(MarketingTypeEnum.CARD.getCode())) {
			return tMarketingCardMapper.selectByPrimaryKey(supportBusinessId);
		} else if (marketingType.equals(MarketingTypeEnum.COUPON_BAG.getCode())) {
			return tMarketingCouponBagMapper.selectByPrimaryKey(supportBusinessId);
		}
		return null;
	}
	
	public TMarketingReceiveHistory selectMarketingReceiveHistoryByPrimaryKey(Long receiveHistoryId,
			Integer marketingType) {
		if (marketingType.equals(MarketingTypeEnum.COUPON.getCode())) {
			return tMarketingReceiveHistoryCouponMapper.selectByPrimaryKey(receiveHistoryId);
		} else if (marketingType.equals(MarketingTypeEnum.CARD.getCode())) {
			return tMarketingReceiveHistoryCardMapper.selectByPrimaryKey(receiveHistoryId);
		} else if (marketingType.equals(MarketingTypeEnum.COUPON_BAG.getCode())) {
			return tMarketingReceiveHistoryCouponBagMapper.selectByPrimaryKey(receiveHistoryId);
		} 
		return null;
	}
	
	protected List<TMarketingUseHistory> selectMarketingUseHistory(TMarketingReceiveHistory tMarketingReceiveHistory) {
		List<TMarketingUseHistory> historyList = new ArrayList<>();
		if (MarketingTypeEnum.COUPON.getCode() == tMarketingReceiveHistory.getMarketingType()) {
			TMarketingUseHistoryCouponExample tMarketingUseHistoryExample = new TMarketingUseHistoryCouponExample();
			tMarketingUseHistoryExample.createCriteria()
					.andStatusEqualTo(Constant.STATUS_YES)
					.andMarketingReceiveHistoryIdEqualTo(tMarketingReceiveHistory.getId())
					.andMarketingIdEqualTo(tMarketingReceiveHistory.getMarketingId());
			List<TMarketingUseHistoryCoupon> tMarketingUseHistoryList = tMarketingUseHistoryCouponMapper
					.selectByExample(tMarketingUseHistoryExample);
			if (!CollectionUtils.isEmpty(tMarketingUseHistoryList)) {
				historyList.addAll(tMarketingUseHistoryList);
			}

		}
		if (MarketingTypeEnum.CARD.getCode() == tMarketingReceiveHistory.getMarketingType()) {
			TMarketingUseHistoryCardExample tMarketingUseHistoryExample = new TMarketingUseHistoryCardExample();
			tMarketingUseHistoryExample.createCriteria()
					.andStatusEqualTo(Constant.STATUS_YES)
					.andMarketingReceiveHistoryIdEqualTo(tMarketingReceiveHistory.getId())
					.andMarketingIdEqualTo(tMarketingReceiveHistory.getMarketingId());
			List<TMarketingUseHistoryCard> tMarketingUseHistoryList = tMarketingUseHistoryCardMapper
					.selectByExample(tMarketingUseHistoryExample);
			if (!CollectionUtils.isEmpty(tMarketingUseHistoryList)) {
				historyList.addAll(tMarketingUseHistoryList);
			}
		}
		return historyList;
	}
	@Override
	public ResponseMessage getUserMarketingReceiveList(MarketingReceiveHistoryParam couponReceiveHistoryExample) {
		return null;
	}

	@Override
	public ResponseMessage getUserMarketingUseDetail(Long receiveHistoryId, Integer marketingType) {
		return null;
	}

	@Override
	public ResponseMessage getMarketingBagUseHisory(Long marketingReceiveHistoryId, Integer marketingType) {
		return null;
	}

	@Override
	public ResponseMessage auditUserMarketing(Long couponBagReceiveHistoryId, Integer marketingType, Integer status) {
		return null;
	}

	@Override
	public ResponseMessage getUserMarketingCardUseHisory(Long userId,Integer pageNum,Integer pageSize) {
		return null;
	}

	@Override
	public ResponseMessage getUserMarketingCouponUseHisory(Long userId,Integer pageNum,Integer pageSize) {
		return null;
	}

	@Override
	public ResponseMessage expireAbolishCoupon() {
		tMarketingUseHistoryMapperSpec.updateDiscardMarketing(MarketingTypeEnum.COUPON.getCode());
		return ResponseMessage.ok();
	}

	@Override
	public ResponseMessage expireAbolishCard() {
		tMarketingUseHistoryMapperSpec.updateDiscardMarketing(MarketingTypeEnum.CARD.getCode());
		return ResponseMessage.ok();
	}
}
